<!--
 * @Descripttion: 编辑问卷
 * @Author: xiao li
 * @Date: 2020-09-28 15:24:24
 * @LastEditors: xiao li
 * @LastEditTime: 2021-11-19 18:39:40
-->

<template>
  <div class="lb-questionnaire-eidt">
    <top-nav :title="navTitle" :isBack="true"></top-nav>
    <div class="page-main">
      <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
        <el-tab-pane label="问卷信息" name="questionnaire">
          <div style="height: 40px"></div>
          <el-form
            @submit.native.prevent
            :model="subForm"
            :rules="subFormRules"
            ref="subForm"
            label-width="160px"
            class="sub-form"
          >
            <el-form-item label="问卷标题" prop="title">
              <el-input
                type="text"
                v-model="subForm.title"
                placeholder="请输入问卷标题"
                maxlength="20"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="问卷封面" prop="cover">
              <lb-cover
                :fileList="subForm.cover"
                @selectedFiles="getCover"
              ></lb-cover>
              <lb-tool-tips>图片建议尺寸: 750 * 420</lb-tool-tips>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                :plain="true"
                @click="subForm.cover = cover"
                >{{ $t('action.defaultImg') }}</el-button
              >
            </el-form-item>
            <el-form-item label="问卷自定义文案" prop="self_text">
              <el-input
                type="textarea"
                :rows="8"
                v-model="subForm.self_text"
                maxlength="100"
                show-word-limit
                resize="none"
                placeholder="请输入问卷自定义文案"
              ></el-input>
            </el-form-item>
            <el-form-item label="问卷结束页文案" prop="end_text">
              <el-input
                type="textarea"
                :rows="8"
                v-model="subForm.end_text"
                maxlength="100"
                show-word-limit
                resize="none"
                placeholder="请输入问卷结束页文案"
              ></el-input>
            </el-form-item>
            <el-form-item label="排序值" prop="top">
              <el-input-number
                class="lb-input-number"
                v-model="subForm.top"
                :controls="false"
                :precision="0"
                :min="0"
                placeholder="请输入排序值"
              ></el-input-number>
              <lb-tool-tips>值越大, 排序越靠前</lb-tool-tips>
            </el-form-item>
            <el-form-item>
              <div class="space-lg"></div>
              <el-button type="primary" @click="submitSubForm">{{
                $t('action.submit')
              }}</el-button>
              <el-button
                type="default"
                style="margin-left: 10px"
                @click="$router.back(-1)"
                >{{ $t('action.back') }}</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="补充题目" name="supplement" v-if="subForm.id">
          <div style="height: 40px"></div>
          <el-row class="page-top-operate ml-lg pl-lg">
            <div class="pb-lg mb-lg" v-if="tableData.length < 1">
              暂无题目数据，请添加
            </div>
            <div
              class="pb-lg mb-lg b-1px-b"
              v-for="(item, index) in tableData"
              :key="index"
            >
              <div>
                <em class="text-normal">{{ index + 1 }}、</em
                >{{ item.title }}（{{ dialogTitle[item.type] }}）<em
                  class="c-warning text-normal"
                  v-if="item.must === 1"
                  >*</em
                >
              </div>
              <block v-if="item.type === 1">
                <div
                  class="pt-lg pb-sm"
                  :class="[{ 'b-1px-t': aindex !== 0 }]"
                  v-for="(aitem, aindex) in item.data_text"
                  :key="aindex"
                >
                  <div>({{ aindex * 1 + 1 }})、{{ aitem.text }}</div>
                  <div
                    class="flex-y-center mb-md"
                    :class="[{ 'mt-md': bindex === 0 }]"
                    v-for="(bitem, bindex) in aitem.ans"
                    :key="bindex"
                  >
                    <i
                      class="
                        iconfont
                        icongouxuan-weixuanzhong-xianxingyuankuang
                        mr-sm
                      "
                    ></i
                    >{{ bitem.text }}
                  </div>
                </div>
              </block>
              <block v-if="item.type === 2">
                <div
                  class="flex-y-center mb-md"
                  :class="[{ 'mt-md': bindex === 0 }]"
                  v-for="(bitem, bindex) in item.data_text"
                  :key="bindex"
                >
                  <div class="flex-y-center">
                    <i
                      class="
                        iconfont
                        icongouxuan-weixuanzhong-xianxingyuankuang
                        mr-sm
                      "
                    ></i
                    >{{ bitem.text }}
                  </div>
                </div>
              </block>
              <block v-if="item.type === 3">
                <div
                  class="mt-lg mb-lg pd-lg radius-15"
                  style="width: 422px; border: 1px solid #f4f6f8"
                >
                  <div class="c-caption" style="min-height: 100px">
                    {{ item.text || '请输入' }}
                  </div>
                  <div class="c-caption text-right">0/200</div>
                </div>
              </block>
              <div :class="[{ 'mt-lg': item.type !== 1 }]">
                <lb-button
                  type="primary"
                  plain
                  @click="toShowDialog(item.type, item)"
                  >{{ $t('action.edit') }}</lb-button
                >
                <lb-button
                  type="danger"
                  plain
                  @click="toDelItem(index, 'tableData')"
                  >{{ $t('action.delete') }}</lb-button
                >
              </div>
            </div>
            <div class="space-lg"></div>
            <lb-button
              type="primary"
              icon="el-icon-plus"
              @click="toShowDialog(1)"
              >矩阵单选题</lb-button
            >
            <lb-button
              type="danger"
              icon="el-icon-plus"
              @click="toShowDialog(2)"
              >联动单选题</lb-button
            >
            <lb-button
              type="success"
              icon="el-icon-plus"
              @click="toShowDialog(3)"
              >填空题</lb-button
            >
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 新增/编辑题目 -->
    <el-dialog
      :title="
        dialogForm.id
          ? `编辑${dialogTitle[cur_type]}`
          : `新增${dialogTitle[cur_type]}`
      "
      :visible.sync="showDialogForm"
      class="dialog-form"
      width="600px"
      @before-close="getQuestionList"
      center
    >
      <el-form
        @submit.native.prevent
        :model="dialogForm"
        :rules="dialogFormRules"
        ref="dialogForm"
        label-width="80px"
      >
        <el-form-item label="题目" prop="title">
          <el-input
            v-model="dialogForm.title"
            placeholder="请输入题目"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序值" prop="top">
          <el-input-number
            class="lb-input-number"
            v-model="dialogForm.top"
            :controls="false"
            :precision="0"
            :min="0"
            placeholder="请输入排序值"
          ></el-input-number>
          <lb-tool-tips>值越大, 排序越靠前</lb-tool-tips>
        </el-form-item>
        <el-form-item label="是否必填" prop="must">
          <el-radio-group v-model="dialogForm.must">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="问题管理" prop="question" v-show="cur_type === 1">
          <el-form-item
            class="pb-lg"
            label=""
            v-for="(item, index) in dialogForm.data_text.que"
            :key="index"
          >
            <el-input v-model="item.text" placeholder="请输入问题"></el-input>
            <lb-button
              class="ml-lg"
              type="danger"
              plain
              @click="toDelItem(index, 'que')"
              >{{ $t('action.delete') }}</lb-button
            >
          </el-form-item>
          <lb-button
            type="primary"
            icon="el-icon-plus"
            @click="toAddItem('que')"
            >新增问题</lb-button
          >
        </el-form-item>
        <el-form-item
          label="答案管理"
          prop="answer"
          v-show="cur_type === 1 || cur_type === 2"
        >
          <el-form-item
            class="pb-lg"
            label=""
            v-for="(item, index) in dialogForm.data_text.ans"
            :key="index"
          >
            <el-input v-model="item.text" placeholder="请输入答案"></el-input>
            <lb-button
              class="ml-lg"
              type="danger"
              plain
              @click="toDelItem(index, 'ans')"
              >{{ $t('action.delete') }}</lb-button
            >
            <el-form-item class="pt-md pb-lg" label="" v-show="cur_type === 2">
              <div
                @click="changeItem(index)"
                class="mr-lg"
                :class="[{ 'c-link': item.is_jump == 1 }]"
                style="cursor: pointer; display: inline-block"
              >
                <div class="flex-y-center">
                  <i
                    class="
                      iconfont
                      icongouxuan-weixuanzhong-xianxingyuankuang
                      mr-sm
                    "
                    :class="[
                      { 'icongouxuan-xuanzhong-yuankuang': item.is_jump == 1 }
                    ]"
                  ></i>
                  答案关联题目
                </div>
              </div>
              <el-select
                v-model="item.jump_id"
                placeholder="请选择跳转题目"
                v-if="item.is_jump === 1"
              >
                <el-option
                  v-for="item in jumpOptions"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                ></el-option>
              </el-select>
              <lb-tool-tips
                >勾选之后，用户选择选项之后，会跳转到指定选项；不勾选，则默认不跳转，按顺序输入下一题
                <div class="c-warning">只能关联排序值低于当前排序值的题目</div>
              </lb-tool-tips>
            </el-form-item>
          </el-form-item>
          <lb-button
            type="primary"
            icon="el-icon-plus"
            @click="toAddItem('ans')"
            >新增答案</lb-button
          >
        </el-form-item>
        <el-form-item label="备注" prop="text" v-show="cur_type === 3">
          <el-input
            type="textarea"
            rows="5"
            resize="none"
            maxlength="100"
            show-word-limit
            v-model="dialogForm.text"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showDialogForm = false">{{
          $t('action.cancel')
        }}</el-button>
        <el-button type="primary" @click="submitDialogForm">{{
          $t('action.comfirm')
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import { mapState } from 'vuex'
export default {
  data () {
    return {
      appPath: '',
      navTitle: '',
      // activeName: 'supplement',
      activeName: 'questionnaire',
      // 基本信息表单值
      cover: [{ url: 'https://lbqny.migugu.com/admin/que/questionnaire.png' }],
      subForm: {
        id: 0,
        title: '',
        cover: [{ url: 'https://lbqny.migugu.com/admin/que/questionnaire.png' }],
        self_text: '为了给您提供更好的服务，希望您能抽出几分钟时间，将您的感受和建议告诉我们，期待您的参与！现在我们就马上开始吧！',
        end_text: '问卷到此结束，感谢您的参与！',
        top: 0,
        status: 1
      },
      // 基本信息验证规则
      subFormRules: {
        title: {
          required: true,
          type: 'string',
          message: '请输入问卷标题',
          trigger: 'blur'
        },
        cover: {
          required: true,
          type: 'array',
          message: '请上传图片',
          trigger: 'change'
        },
        self_text: {
          required: true,
          type: 'string',
          message: '请输入问卷自定义文案',
          trigger: 'blur'
        },
        end_text: {
          required: true,
          type: 'string',
          message: '请输入问卷结束页文案',
          trigger: 'blur'
        },
        top: {
          required: true,
          type: 'number',
          message: '请输入排序值',
          trigger: 'blur'
        }
      },
      tableData: [],
      jumpOptions: [{ id: -1, title: '跳转至问卷末尾，结束问答' }],
      showDialogForm: false,
      dialogTitle: {
        1: '矩阵单选题',
        2: '联动单选题',
        3: '填空题'
      },
      cur_type: 1,
      dialogForm: {
        id: 0,
        q_id: 0,
        type: 2,
        title: '',
        top: 0,
        must: 1,
        data_text: {
          que: [],
          ans: []
        },
        text: ''
      },
      dialogFormRules: {
        title: {
          required: true,
          type: 'string',
          message: '请输入题目',
          trigger: 'blur'
        },
        must: {
          required: true
        },
        top: {
          required: true,
          type: 'number',
          message: '请输入排序值',
          trigger: 'blur'
        }
      }
    }
  },
  async created () {
    let { id } = this.$route.query
    this.subForm.id = id
    this.navTitle = this.$t(id ? 'menu.QuestionNaireEdit' : 'menu.QuestionNaireAdd')
    if (!id) return
    await this.getDetail()
  },
  computed: {
    ...mapState({
      routesItem: state => state.routes
    })
  },
  methods: {
    /**
     * @method 获取详情
     */
    async getDetail () {
      let { id = 0 } = this.subForm
      if (!id) return
      let { code, data } = await this.$api.appointmentQuestionInfo({ id })
      if (code !== 200) return
      data.cover = [{ url: data.cover }]
      for (let key in this.subForm) {
        this.subForm[key] = data[key]
      }
    },
    handleClick (e) {
      let key = e.label === '问卷信息' ? 'questionnaire' : 'supplement'
      if (key === 'questionnaire' && this.subForm.id) {
        this.getDetail()
      } else {
        this.getQuestionList()
      }
    },
    /**
     * @method 获取封面图
     */
    getCover (img) {
      this.subForm.cover = img
    },
    /**
     * @method 提交信息
     */
    async submitSubForm () {
      let title = JSON.parse(JSON.stringify(this.subForm.title)).replace(/^\s+|\s+$/g, '')
      this.subForm.title = title
      let subForm = JSON.parse(JSON.stringify(this.subForm))
      let formArr = ['subForm']
      let flag = true
      for (let i = 0, len = formArr.length; i < len; i++) {
        this.$refs[formArr[i]].validate(valid => {
          if (!valid) {
            flag = false
            return false
          }
        })
      }
      if (flag) {
        subForm.cover = subForm.cover[0].url
        let methodModel = subForm.id ? 'appointmentQuestionUpdate' : 'appointmentQuestionAdd'
        let { code, data } = await this.$api[methodModel](subForm)
        if (code !== 200) return
        this.subForm.id = subForm.id ? subForm.id : data
        this.$message.success(this.$t(subForm.id ? 'tips.successRev' : 'tips.successSub'))
        this.activeName = 'supplement'
        this.getQuestionList()
      }
    },
    /**
     * @method: 获取问卷关联题目
     */
    async getQuestionList () {
      let { id } = this.subForm
      let { code, data } = await this.$api.appointmentQueTextListInfo({ id })
      if (code !== 200) return
      this.tableData = data
    },
    /**
     * @method: 添加题目弹窗
     * @param {*} type 1矩阵单选题；2联动单选题目；3填空题
     */
    async toShowDialog (type, item = {
      id: 0,
      q_id: 0,
      type: 1,
      title: '',
      top: 0,
      must: 1,
      data_text: {
        que: [],
        ans: []
      },
      text: ''
    }) {
      if (item.id) {
        item = JSON.parse(JSON.stringify(item))
        if (item.type === 3) {
          item.data_text = { que: [], ans: [] }
        } else {
          let que = item.type === 1 ? item.data_text.map(item => {
            return { text: item.text }
          }) : []
          let ans = item.type === 1 ? item.data_text[0].ans.map(item => {
            return { text: item.text }
          }) : item.data_text.map(item => {
            return { text: item.text, is_jump: item.is_jump, jump_id: item.jump_id }
          })
          item.data_text = { que, ans }
        }
        if (item.type === 2) {
          await this.getJumpList(item.id)
        }
      } else {
        item.type = type
        this.jumpOptions = [{ id: -1, title: '跳转至问卷末尾，结束问答' }]
      }
      this.cur_type = type
      for (let key in this.dialogForm) {
        this.dialogForm[key] = item[key]
      }
      this.showDialogForm = type
    },
    /**
     * @method: 新增问题/答案
     * @param {*} key
     */
    toAddItem (key) {
      let item = this.cur_type === 2 ? {
        text: '',
        is_jump: 0,
        jump_id: ''
      } : { text: '' }
      this.dialogForm.data_text[key].push(item)
    },
    /**
     * @method: 删除问题/答案
     * @param {*} index
     * @param {*} key
     */
    toDelItem (index, key) {
      if (key === 'tableData') {
        this.toDel(index)
      } else {
        this.dialogForm.data_text[key].splice(index, 1)
      }
    },
    async toDel (index) {
      let { id } = this.tableData[index]
      this.$confirm(this.$t('tips.confirmDelete'), this.$t('tips.reminder'), {
        confirmButtonText: this.$t('action.comfirm'),
        cancelButtonText: this.$t('action.cancel'),
        type: 'warning'
      }).then(() => {
        this.$api.appointmentQueTextDel({ id }).then(res => {
          if (res.code === 200) {
            this.$message.success(this.$t('tips.successOper'))
            this.getQuestionList()
          }
        })
      }).catch(() => {

      })
    },
    /**
     * @method: 获取关联题目
     * @param {*} id
     */
    async getJumpList (id) {
      let { id: qid } = this.subForm
      let { code, data } = await this.$api.appointmentJumpSelectText({ q_id: qid, id })
      if (code !== 200) return
      data.unshift({
        id: -1,
        title: '跳转至问卷末尾，结束问答'
      })
      this.jumpOptions = data
    },
    /**
     * @method: 答案关联跳转题目
     * @param {*} e
     * @param {*} index
     */
    changeItem (index) {
      let jump = this.dialogForm.data_text.ans[index].is_jump
      this.dialogForm.data_text.ans[index].is_jump = jump === 0 ? 1 : 0
    },
    /**
     * @method: 新增/编辑题目
     */
    async submitDialogForm () {
      this.dialogForm.title = this.dialogForm.title.replace(/^\s+|\s+$/g, '')
      let subForm = JSON.parse(JSON.stringify(this.dialogForm))
      subForm.q_id = this.subForm.id
      if (subForm.type !== 3) {
        delete subForm.text
      }
      let formArr = ['dialogForm']
      let flag = true
      for (let i = 0, len = formArr.length; i < len; i++) {
        this.$refs[formArr[i]].validate(valid => {
          if (!valid) {
            flag = false
            return false
          }
        })
      }
      if (flag) {
        if (subForm.type === 1 && (subForm.data_text.que.length === 0 || subForm.data_text.que.filter(item => {
          return !item.text.replace(/^\s+|\s+$/g, '')
        }).length > 0)) {
          this.$message.error(`请输入问题`)
          return
        }
        if (subForm.type !== 3 && (subForm.data_text.ans.length === 0 || subForm.data_text.ans.filter(item => {
          return !item.text.replace(/^\s+|\s+$/g, '')
        }).length > 0)) {
          this.$message.error(`请输入答案`)
          return
        }
        let methodModel = subForm.id ? 'appointmentQueTextUpdate' : 'appointmentQueTextAdd'
        let { code } = await this.$api[methodModel](subForm)
        if (code !== 200) return
        this.$message.success(this.$t(subForm.id ? 'tips.successRev' : 'tips.successSub'))
        this.showDialogForm = false
        this.getQuestionList()
      }
    }
  },
  filters: {
    handleTime (val, type) {
      let time = type === 1 ? moment(val * 1000).format('YYYY-MM-DD') : type === 2 ? moment(val * 1000).format('HH:mm:ss') : moment(val * 1000).format('YYYY-MM-DD HH:mm:ss')
      return time
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-questionnaire-eidt {
  width: 100%;
  padding-bottom: 0px;
  position: relative;
  .el-form {
    margin: 20px 0;
  }
  .iconfont {
    font-size: 20px;
  }
  .sub-form {
    .el-input,
    .el-input-number,
    .el-cascader,
    .el-select {
      width: 300px;
    }
    .el-textarea {
      width: 600px;
    }
  }

  .dialog-form {
    .el-select {
      width: 268px;
    }
    .el-input,
    .el-input-number,
    .el-cascader {
      width: 300px;
    }
    .el-textarea {
      width: 450px;
    }
  }
}
</style>
